package com.ymttest.database.sharding;

import io.shardingjdbc.core.api.algorithm.sharding.ListShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.ymt.core.tool.Logger;

/**
 * Created by zhangyifan on 2017/12/4.
 */
public class ComplexKeysTableAlgorithm extends ComplexKeysAlgorithm {

	@Override
	protected Collection<String> doInSharding(
			final Collection<String> availableTargetNames,
			final ListShardingValue<Long> shardingValues) {

		List<String> result = new ArrayList<String>();

		if (availableTargetNames.size() == 1) {
			String targetName = availableTargetNames.iterator().next();
			shardingValues.getValues().forEach(v -> result.add(targetName));
			return result;
		}

		//123456789 -%100-> 89 -> order_89
		for (Long value : shardingValues.getValues()) {
			boolean hit = false;
			long index = value % 100;
			for (String each : availableTargetNames) {
				if (each.endsWith("_" + index)) {
					result.add(each);
					hit = true;
					break;
				}
			}
			if (!hit) {
				throw new RuntimeException(
						"No target table found for shardingValue:" + value);
			}
		}

		Logger.info(String.format("数据库表为: %s", result));

		return result;
	}
}
